package com.lanou3g.code0418.control;

import java.util.concurrent.RecursiveTask;

/**
 * Created by dllo on 18/4/18.
 */
public class SumTask extends RecursiveTask<Long> {
    private long target;
    private long from;
    //阈值,如果from和target的差>该值,则拆分任务
    private static final long THRESHOLD = 100000L;

    public SumTask(long from, long target) {
        this.from = from;
        this.target = target;
    }

    @Override
    protected Long compute() {
        if (target - from < THRESHOLD) {
            //任务已经足够小了
            //自己计算完成即可
            long sum = 0L;
            for (long i = from; i <= target; i++) {
                sum += i;
            }
            return sum;
        }
        //任务还是很大,需要拆分
        SumTask sumTask1 = new SumTask(from, (target + from) / 2);
        SumTask sumTask2 = new SumTask((target + from) / 2 + 1, target);
        //相当于 线程.start();
        invokeAll(sumTask1, sumTask2);//关键代码
        return sumTask1.join() + sumTask2.join();
    }
}
